package org.codefinger.dao.impl.sql.ast;

import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Expression;

public class ListExpression implements Expression {

	private Expression[]	params;

	public ListExpression(Expression[] params) {
		super();
		this.params = params;
	}

	@Override
	public boolean matchVisit(SQLVisitor visitor) {
		int sqlSize = visitor.getSqlSize();
		int paramSize = visitor.getParamSize();
		visitor.appendSQL("(");
		int length = params.length;
		if (length == 1) {
			if (params[0].matchVisit(visitor)) {
				visitor.appendSQL(')');
				return true;
			}
			visitor.back(sqlSize, paramSize);
			return false;
		}
		boolean flag = false;
		for (Expression param : params) {
			if (flag) {
				visitor.appendSQL(',');
				if (!param.matchVisit(visitor)) {
					if (flag) {
						visitor.back(visitor.getSqlSize() - 1);
					}
				}
				continue;
			}
			if (param.matchVisit(visitor)) {
				flag = true;
			}
		}
		if (flag) {
			visitor.appendSQL(')');
			return true;
		} else {
			visitor.back(sqlSize, paramSize);
			return false;
		}
	}

	@Override
	public void visit(SQLVisitor visitor) {
		Expression[] params = this.params;
		visitor.appendSQL("(");
		int length = params.length;
		if (length == 1) {
			params[0].visit(visitor);
			visitor.appendSQL(')');
			return;
		}
		params[0].visit(visitor);
		for (int i = 1; i < length; i++) {
			visitor.appendSQL(',');
			params[i].visit(visitor);
		}
		visitor.appendSQL(')');
	}

}
